import { defineStore } from "pinia"
import type { LoginFormData, LoginResponseData } from "@/api/user/type"
import type { userState } from "@/store/modules/types/type"
import { reqLogin, reqLogout, reqUserInfo } from "@/api/user"
import { GET_TOKEN, REMOVE_TOKEN, SET_TOKEN } from "@/utils/token"
import { routes } from "@/router/routes"

const useUserStore = defineStore("User", {
    state: (): userState => {
        return {
            token: GET_TOKEN(),
            menuRoute: routes,
            username: "",
            avatar: "",
        }
    },
    actions: {
        async userLogin(form: LoginFormData) {
            const result: LoginResponseData = await reqLogin(form)
            if (result.code == 200) {
                this.token = result.data as string
                SET_TOKEN(this.token)
                return "ok"
            }
            return Promise.reject(new Error(result.data ?? result.message))
        },

        async userLogout() {
            await reqLogout()
            this.token = ""
            this.username = ""
            this.avatar = ""
            REMOVE_TOKEN()
        },

        async userInfo() {
            const result = await reqUserInfo()
            if (result.code == 200) {
                this.username = result.data?.name ?? ""
                this.avatar = result.data?.avatar ?? ""
                return "ok"
            }
            return Promise.reject(new Error(result.message))
        },
    },
    getters: {},
})

export default useUserStore
